package com.easylinkin.linkappapi.lobar.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.lobar.service.UserLoginService;
import com.easylinkin.linkappapi.lobar.util.HttpUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("UserLoginService")
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    private RestTemplate restTemplate = new RestTemplate();

    @Value("${safetyweb.url}")
    private String compHost;

    @Value("${jdparam.tokenUrl}")
    private String tokenUrl;

    @Value("${jdparam.tokenPath}")
    private String tokenPath;

    @Value("${jdparam.clientId}")
    private String clientId;

    @Value("${jdparam.clientSecret}")
    private String clientSecret;

    @Value("${jdparam.redirectUri}")
    private String redirectUri;

    @Value("${jdparam.tokenUrl}")
    private String userInfoUrl;

    @Value("${jdparam.userInfoPath}")
    private String userInfoPath;

    public RestMessage userCheck(String ticket, String token) throws Exception {
        // 如果token不为null，则先查询redis中是否有用户登录信息，如果有，则直接放行
        // 如果没有，则token过期
        if (token != null) {
            Object isLogin = redisTemplate.opsForValue().get(token);
            if (isLogin != null) {
                return RestBuilders.successBuilder().data(token).build();
            } else {
                return RestBuilders.failureBuilder("401").message("用户登录已过期").build();
            }
        }

        if (ticket != null) {
            // redis中没有用户的登录信息，需要调接口进行校验
            // 1、通过ticket获取token
            Map<String, String> querys = new HashMap<>();
            querys.put("client_id", clientId);
            querys.put("client_secret", clientSecret);
            querys.put("code", ticket);
            querys.put("grant_type", "authorization_code");
            querys.put("redirect_uri", redirectUri);
            HttpResponse response = HttpUtils.doGet(tokenUrl, tokenPath, "GET", new HashMap<>(), querys);
            //获取response的body
            JSONObject result = JSON.parseObject(EntityUtils.toString(response.getEntity()));
            String status = result.getString("status");
            String accessToken = "";
            Long expires;
            if (result != null && status.equals("200")) {
                accessToken = result.getString("access_token");
                expires = result.getLong("expires");
            } else {
                return RestBuilders.failureBuilder("401").build();
            }

            // 2、通过token获取用户信息（工号以及用户登陆过期时间）
            Map<String, String> querys2 = new HashMap<>();
            querys2.put("access_token", accessToken);
            HttpResponse response2 = HttpUtils.doGet(userInfoUrl, userInfoPath, "GET", new HashMap<>(), querys2);
            //获取response的body
            JSONObject result2 = JSON.parseObject(EntityUtils.toString(response2.getEntity()));
            String status2 = result2.getString("status");
            String workCode = "";
            if (result2 != null && status2.equals("200")) {
                // 获取工号以及过期时间
                JSONObject resp = result2.getJSONObject("attributes");
                workCode = resp.getString("workcode");

            } else {
                return RestBuilders.failureBuilder("401").message("未查到用户信息").build();
            }

            // 3、根据工号去企业端系统里查询该用户是否有查看权限
            // 转发到企业端
            JSONObject userObject = restTemplate.getForObject(compHost + "userRight/getUserRight?workCode=" + workCode, JSONObject.class);
            JSONArray dataArray = userObject.getJSONArray("data");
            List<String> data = new ObjectMapper().readValue(dataArray.toString(), new TypeReference<List<String>>(){});
            if (data.contains("enterpriseDashboard")) {
                // 如果用户有权限，则存到redis中
                // 4、redis中存储token以及用户的信息，过期时间以token过期时间为准
                redisTemplate.opsForValue().set(accessToken, workCode, expires, TimeUnit.SECONDS);
            } else {
                return RestBuilders.failureBuilder("401").message("该帐号没有权限").build();
            }

            return RestBuilders.successBuilder().data(accessToken).build();
        } else {
            return RestBuilders.failureBuilder("401").message("未查到用户信息").build();
        }

    }
}
